
import React, { Component } from "react";
import { connect } from "react-redux";
import { Card, Button, Table, Modal, Form, Input, Tree, message } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import dayjs from "dayjs";
import { reqRoleAdd, reqRoleList, reqRoleUpdate } from "../../api";
import { PAGE_SIZE } from "../../config";
const { Item } = Form;

@connect(
    state => ({ username: state.userInfo.user.username }),
    {}
)
class Role extends Component {

    state = {
        columnConfig: [
            {
                dataIndex: "name",
                title: "角色名称",
                key: "name"
            },
            {
                dataIndex: "create_time",
                title: "创建时间",
                key: "create_time",
                render: time => dayjs(time).format("YYYY-MM-DD HH:mm:ss")
            },
            {
                dataIndex: "auth_time",
                title: "授权时间",
                key: "auth_time",
                render: time => dayjs(time).format("YYYY-MM-DD HH:mm:ss")
            },
            {
                dataIndex: "auth_name",
                title: "授权人",
                key: "auth_name"
            },
            {
                title: "操作",
                key: "caozuo",
                render: item => {
                    return (
                        <Button
                            type="link"
                            onClick={() => {
                                this.setState(
                                    {
                                        checkedKeys: item.menus.map(v => {
                                            if (v === "all") return "all";
                                            return "/" + v.split("/").reverse()[0];
                                        }),
                                        isShowAuth: true,
                                        currentRoleId: item._id
                                    }
                                )
                            }}
                        >
                            设置权限
                        </Button>
                    )
                }
            }
        ],
        //角色权限树，按照antd Tree组件的格式配置，key为传到数据库中保留的内容
        allMenu: [
            {
                title: "全部",
                key: "all",
                children: [
                    {
                        title: "首页",
                        key: "/home",
                    },
                    {
                        title: "用户管理",
                        key: "/user",
                    },
                    {
                        title: "角色管理",
                        key: "/role",
                    },
                    {
                        title: "图表",
                        key: "/charts",
                        children: [
                            {
                                title: "柱状图",
                                key: "/bar",
                            },
                            {
                                title: "折线图",
                                key: "/line",
                            },
                            {
                                title: "饼状图",
                                key: "/pie",
                            },
                        ]
                    },
                    {
                        title: "订单管理",
                        key: "/order",
                    },
                    {
                        title: "商品",
                        key: "/products",
                        children: [
                            {
                                title: "分类管理",
                                key: "/category"
                            },
                            {
                                title: "商品管理",
                                key: "/product"
                            }
                        ]
                    }
                ]
            }
        ],
        //角色列表
        roleList: [],
        //增加弹框控制
        isShowAdd: false,
        //权限树弹框控制
        isShowAuth: false,
        //已选权限
        checkedKeys: [],
        //当前操作权限的角色id
        currentRoleId: ""
    }

    formRef = React.createRef();

    /**
     * 获取角色列表
     */
    getRoleList = async () => {
        let result = await reqRoleList();
        this.setState({ roleList: [...result.reverse()] });
    }

    /**
     * 增加角色弹框的确认监听
     * 确认时提交表单
     */
    onButtonAddConfirmClick = () => {
        this.formRef.current.submit();
    }

    /**
     * 增加角色弹框的取消监听
     * 取消时将表单重置
     */
    onButtonAddCancelClick = () => {
        this.setState({ isShowAdd: false })
        this.formRef.current.resetFields();
    }

    /**
     * 角色权限弹框的确认监听
     * 更新权限后发送请求
     * this.state.checkKeys在点击修改权限时将item.menus赋给它
     */
    onButtonAuthConfirmClick = async () => {
        //这里做一个处理，在this.state.checkKeys中是扁平化数组，没有上下级关系例如：[/charts,/pie,/bar]
        //而到数据库中存储的是[/charts,/charts/pie,/charts/bar]
        let menus = this.state.checkedKeys.map(v => {
            if (v === "/pie" || v === "/bar" || v === "/line")
                return "/charts" + v;
            if (v === "/category" || v === "/product")
                return "/products" + v;
            return v
        })
        if (menus.length === 0) {
            message.error("至少要选择一个权限", 1);
        } else {
            let _id = this.state.currentRoleId;
            let auth_name = this.props.username;
            let roleResult = await reqRoleUpdate(_id, menus, auth_name)
            if (roleResult) {
                let newRoleList = this.state.roleList.filter(v => {
                    return v._id !== _id
                })
                newRoleList.unshift(roleResult);
                this.setState({ isShowAuth: false, currentRoleId: "", roleList: newRoleList });
            }
        }
    }

    /**
     * 角色权限弹框的取消监听
     */
    onButtonAuthCancelClick = () => {
        this.setState({ isShowAuth: false})
    }

    /**
     * 增加角色，表单数据通过rules验证成功后的回调
     * 在此发送增加角色请求
     */
    onFinish = async () => {
        let roleName = this.formRef.current.getFieldValue();
        let result = await reqRoleAdd(roleName);
        let newList = [...this.state.roleList];
        newList.unshift(result);
        this.setState({ roleList: newList, isShowAdd: false });
        this.formRef.current.resetFields();
    }

    /**
     * 增加角色表单数据未通过rules验证的回调
     */
    onFinishFailed = () => {
        //验证错了啥也不做
    }

    /**
     * tree组件的选中与否监听
     * @param {选中的权限菜单} checkedKeys 
     * @returns 返回选中的权限数组
     */
    onCheck = (checkedKeys) => this.setState({ checkedKeys });

    componentDidMount() {
        this.getRoleList();
    }

    render() {
        return (
            <div>
                <Card
                    title={
                        <Button
                            type="primary"
                            icon={<PlusOutlined />}
                            onClick={
                                () => {
                                    this.setState({ isShowAdd: true })
                                }
                            }
                        >
                            新增角色
                        </Button>
                    }
                >
                    <Table
                        columns={this.state.columnConfig}
                        rowKey="_id"
                        bordered
                        dataSource={this.state.roleList}
                        pagination={
                            {
                                pageSize: PAGE_SIZE,
                                showQuickJumper: true
                            }
                        }
                    />
                </Card>
                <Modal
                    title="新增角色"
                    visible={this.state.isShowAdd}
                    okText="确定"
                    cancelText="取消"
                    onOk={this.onButtonAddConfirmClick}
                    onCancel={this.onButtonAddCancelClick}
                >
                    <Form ref={this.formRef} name="horizontal_login" onFinish={this.onFinish} onFinishFailed={this.onFinishFailed}>
                        <Item
                            label="角色名"
                            name="roleName"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入角色',
                                },
                                {
                                    pattern: /^[\w+$\u4e00-\u9fa5]/,
                                    message: "角色名是汉字、字母、数字、下划线组成"
                                }
                            ]}
                        >
                            <Input placeholder="请输入角色名" />
                        </Item>
                    </Form>
                </Modal>
                <Modal
                    title="设置权限"
                    visible={this.state.isShowAuth}
                    okText="确定"
                    cancelText="取消"
                    onOk={this.onButtonAuthConfirmClick}
                    onCancel={this.onButtonAuthCancelClick}
                >
                    <Tree
                        defaultExpandAll={true}
                        checkable
                        onCheck={this.onCheck}
                        checkedKeys={this.state.checkedKeys}
                        treeData={this.state.allMenu}
                    />
                </Modal>
            </div>
        )
    }
}
export default Role;